<template>
  <div class="app animate__animated" :class="{'animate__flipOutY': enter, 'animate__flipInY': !enter}"  v-if="!hide"></div>
  <router-view v-if="enter"></router-view>
  <md-popup v-model="parent.show" position="bottom" :mask-closable="false">
    <md-popup-title-bar :title="$t('parent.wallet')" :describe="$t('parent.describe')" title-align="left" />
    <div style="background: #fff; padding: 20px">
      <md-input-item v-model="parent.wallet" :placeholder="$t('parent.wallet')" is-highlight></md-input-item>
      <div style="padding-top: 20px">
        <md-button type="primary" :loading="parent.loading" @click="reg" round>{{ $t('confirm') }}</md-button>
      </div>
    </div>
  </md-popup>
</template>

<script setup>
  import { ref, watch } from 'vue'
  import { useRoute } from 'vue-router'
  import { init, wallet, makeAuth } from '@/web3'
  import { toast } from '@/style'
  import { t } from '@/lang'

  import { boot, debug, initUpdate } from '@/model/index'
  import { userInfo } from '@/model/user'
  import { register } from '@/api/user'

  const route = useRoute()
  const enter = ref(false)
  const hide = ref(false)
  
  // 上级
  const parent = ref({
    show: false,
    loading: false,
    wallet: ''
  })
  
  // 监听 url 传入种子钱包
  watch(() => route.query, () => {
      parent.value.wallet = route.query.wallet
    }
  )

  // 进入系统
  const main = () => {
    // 进入
    enter.value = true

    // 隐藏开屏
    setTimeout(() => {
      debug(0)
      toast(false)
      hide.value = true
    }, 1000)
  }

  // 登陆 
  const login = async() => {
    toast(t('userinfo'), 'ring', 0)
    // 请求用户信息
    userInfo().then(main)
  }
  
  // 注册用户
  const reg = () => {
    parent.value.loading = true
    register(wallet.value, parent.value.wallet).then(res => {
      // 不显示注册层
      parent.value.show = false
      // 再次登陆
      login()
    }).catch(() => {
      toast(t('parenterror'))
    }).finally(() => {
      parent.value.loading = false
    })
  }
  
  // 授权
  const auth = async() => {
    toast(t('auth'), 'ring', 0),
    // 生成令牌
    await makeAuth()
    // 开始登陆 
    login()
  }
    
  // 进入引导
  watch(boot, () => {
    if(boot.value) {
      enter.value = false
      hide.value = false
      const callback = [0,
        // 维护模式
        () => toast(t('dev'), 'spinner', 0),
        // 进行授权
        () => auth(),
        // 拉黑模式
        () => toast(t('black'), 'check-disabled', 0),
        // 注册模式，显示注册层
        () => { toast(false); parent.value.show = true }
      ]
      callback[boot.value]()
    }
  })
  
  // 启动加载
  toast(t('main'), 'ring', 0)
  initUpdate().then(res => {
    // 加载 web3 及 用户登陆
    init(login)
  })
</script>

<style lang="scss" scoped>
  .app{
    width: 100%;
    min-height: 100%;
    background: url(@/assets/app.jpg) center no-repeat;
    background-size: cover;
    position: fixed;
    overflow: hidden;
    z-index: 100;
  }
</style>